// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2005-01-31

#include "stdafx.h"
#include <common/svr_base/svr_showinfo.h>
#include <common/svr_base/db_utility.h>
#include "msvr_server.h"
#include "msvr_room.h"
#include "msvr_user.h"
#include "dbmsg_mainhandler.h"
#include "ui_mainwnd.h"
#include "ui_attribitem.h"

namespace JoyServer
{

class CJoyMsgWndExecRoomLoad
    : public CJoyMsgWndExec
{
public:
    int m_roomId;
    CJoyMainServer* m_server;

    virtual ~CJoyMsgWndExecRoomLoad()
    {
    }
    virtual void Execute()
    {
        CJoyMainWnd* serverWnd = (CJoyMainWnd*)m_server->m_serverWnd;

        CJoyAutoCS gate(m_server->m_userSetsLock);
        CJoyMainServer::CRoomMap& rooms = m_server->m_rooms;
        CJoyMainRoom* pRoom;
        if(!rooms.Lookup(m_roomId, pRoom))
        {
            return;
        }
        
        JoyServerAttrib::Attrib_Room* ar = NULL;
        serverWnd->CreateAttrib(ar);
        ar->Load(pRoom);
        serverWnd->m_roomItems.AddTail(ar);
    }
};

void CJoyDbMsgMainHandler::OnDbMsg_RoomLoad(const CJoyDbMsg& msg)
{
    CJoyXmlElement* root = msg.m_root;
    if(root == NULL)
    {
        m_server->m_showInfo->QueueTimeColorText(InfoColor_Error,
            "bad room note format. <%s>.\n", (PCSTR) msg.m_content);
        return;
    }
    int roomId = root->GetElement("room")->ReadIntD("room_id", 0);
	
	if(roomId == 0)
    {
        m_server->m_showInfo->QueueTimeColorText(InfoColor_Error,
            "bad room id to load.\n");
        return;
    }

    CJoyMainServer* pServer = GetServer();

    CJoyDbSession servSess;
    if(!JoyOpenDbSession(pServer, servSess, pServer->m_dbServer))
    {
        return;
    }

    CJoyDbCommand roomRow;
    if(!JoyInvokeCommand(pServer, servSess, roomRow,
        L"select_room", roomId))
    {
        return;
    }
    if(!HasMoreRow(roomRow.MoveNext()))
    {
        return;
    }

    CJoyDbSession onlineSess;
    if(!JoyOpenDbSession(pServer, onlineSess, pServer->GetOnlineDbSource()))
    {
        return;
    }

    pServer->CreateRoom(onlineSess, roomRow);

    CJoyMsgWndExecRoomLoad* pRoomLoad = new CJoyMsgWndExecRoomLoad();
    pRoomLoad->m_roomId = roomId;
    pRoomLoad->m_server = pServer;
    pServer->m_mainThreadWnd->PostExec( pRoomLoad );

}



} // namespace JoyServer